package sqlitedb

import (
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/os/glog"
	"github.com/sirupsen/logrus"
	terlog "gitlab.local/DO-module/new-filemanage-module/src/core/logger"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

// PgDsn 数据库配置 #SQL@TerraMaster.2021#
// const DbDsn = "file:/etc/base/nasdb?charset=utf8&cache=shared&parseTime=True&loc=Local&_busy_timeout=6000&_foreign_keys=true"
const PgDsn = "host=127.0.0.1 user=terramaster dbname=tos port=5032 sslmode=disable"
const MediaDsn = "host=127.0.0.1 user=postgres dbname=postgres port=5432 sslmode=disable"

//const PgDsn = "host=10.18.13.40 user=terramaster password=SQL@TerraMaster.2021 dbname=tos port=5032 sslmode=disable"

type Getter interface {
	DbGet() *gorm.DB
	CloseDb() error
}

type SqliteDb struct {
	Db *gorm.DB
}

// New 创建一个新的数据库连接(常驻内存)
func New() (*SqliteDb, error) {
	level := logger.Warn
	if terlog.IsDebug() {
		level = logger.Info
	}
	//禁用表名加s后缀
	db, e := gorm.Open(
		postgres.Open(PgDsn),
		&gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true, //禁用表名加s后缀
			},
			SkipDefaultTransaction: false, //默认事务
			PrepareStmt:            true,  //预编译语句
			Logger: logger.New(
				log.New(os.Stdout, "\r\n", log.LstdFlags),
				logger.Config{
					SlowThreshold: time.Second, //设置sql执行时间超过1s的打印日志
					LogLevel:      level,       //设置日志打印级别
					Colorful:      true,        //设置日志打印颜色
				},
			),
		})
	if e != nil {
		return nil, gerror.Wrap(e, "New")
	}
	d, e := db.DB()
	if e != nil {
		return nil, gerror.Wrap(e, "New1")
	}

	//连接池配置,一定要配置，要不然连接无上限，还不能及时回收连接
	d.SetMaxOpenConns(10)
	d.SetMaxIdleConns(2)
	d.SetConnMaxIdleTime(time.Minute)
	d.SetConnMaxLifetime(time.Minute * 3)

	if e = d.Ping(); e != nil {
		return nil, gerror.Wrap(e, "New2")
	}
	sqliteDb := &SqliteDb{Db: db}
	//执行表迁移
	if e = sqliteDb.tableMigration(); e != nil {
		glog.Warning(e)
	}
	return sqliteDb, nil
}

// MediaDB 连接media数据库
func MediaDB() (*gorm.DB, error) {
	level := logger.Warn
	if terlog.IsDebug() {
		level = logger.Info
	}
	//禁用表名加s后缀
	db, e := gorm.Open(
		postgres.Open(MediaDsn),
		&gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true, //禁用表名加s后缀
			},
			SkipDefaultTransaction: false, //默认事务
			PrepareStmt:            true,  //预编译语句
			Logger: logger.New(
				logrus.StandardLogger(),
				logger.Config{
					SlowThreshold: time.Second, //设置sql执行时间超过1s的打印日志
					LogLevel:      level,       //设置日志打印级别
					Colorful:      true,        //设置日志打印颜色
				},
			),
		})
	if e != nil {
		return nil, gerror.Wrap(e, "MediaDB")
	}
	d, e := db.DB()
	if e != nil {
		return nil, gerror.Wrap(e, "MediaDB1")
	}

	//连接池配置,一定要配置，要不然连接无上限，还不能及时回收连接
	d.SetMaxOpenConns(5)
	d.SetMaxIdleConns(1)
	d.SetConnMaxIdleTime(time.Minute)
	d.SetConnMaxLifetime(time.Minute * 2)

	if e = d.Ping(); e != nil {
		return nil, gerror.Wrap(e, "MediaDB2")
	}
	return db, nil
}
